#include <stdio.h>
#include <dlfcn.h>
#include <string.h>

#define MAX_STRING	200
#define LIB_PATH	"libs/"

void invoke_method(char *lib, char *method, double a, double b);

int main(int argc, char *argv[])
{
	char line[MAX_STRING + 1];
	char method[MAX_STRING];
	char lib[MAX_STRING] = LIB_PATH;
	double a;
	double b;
	
	while (1) {
		printf("> ");
		line[0] = 0;
		fgets(line, MAX_STRING, stdin);
		if (!strncmp(line, "end", 3)) break;
			sscanf(line, "%lf %s %lf", &a, method, &b);
			
			/* Create path to folder with libraries */
		
			strcat(lib, method);
			strcat(lib, "lib.so");
		
			//printf("\nmethod: %s\n", method);
			//printf("lib: %s\n", lib);
			//printf("line: %s", line);
			//printf("a is: %f\n", a);
			//printf("b is: %f\n", b);
			
			invoke_method(lib, method, a, b);
			
			memcpy(lib, LIB_PATH, sizeof(LIB_PATH));
			
			}
}

void invoke_method(char *lib, char *method, double a, double b)
{
	void *dl_handle;
	double (*func)(double, double);
	char *error;

/* Open shared library */

	dl_handle = dlopen( lib, RTLD_LAZY );
	if (!dl_handle) {
		printf("*** ERROR: %s ***\n", dlerror() );
	return;
	}

/* Find the address of a function in the library */

	func = dlsym( dl_handle, method );
	error = dlerror();
	if (error != NULL) {
		printf("*** ERROR: %s ***\n", error );
	return;
	}

/* Call the function found at and print the result */

	printf("\nresult is: %f\n", (*func)(a, b));

/* Close used library */
	
	dlclose(dl_handle);
	return;
}